package com.itheima.sh.esdemo;

import com.alibaba.fastjson.JSON;
import com.itheima.sh.esdemo.pojo.Sku;
import com.itheima.sh.esdemo.service.SearchService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RunWith(value = SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {SearchApplication.class})
public class addSku {

    @Autowired
    private SearchService searchService;

    @Test
    public void t() {
        Map map = searchService.findSkuPage(1, 100);
        long total = (long) map.get("total");
        System.out.println(total);
    }
    @Test
    public void addSkumethod() throws Exception {
        Integer pageSize = 10000;
        Map map = searchService.findSkuPage(1, pageSize);
//        获得总条数
        long total = (long) map.get("total");
        if (total > pageSize) {
            for (int i = 1; i <= total / pageSize + 1; i++) {
                map = searchService.findSkuPage(i, pageSize);
                List<Sku> records = (List<Sku>) map.get("records");
                BulkRequest bulkRequest = new BulkRequest();
                for (Sku sku : records) {
                    bulkRequest.add(new IndexRequest("sku")
                            .id(sku.getId())
                            .source(JSON.toJSONString(sku), XContentType.JSON));
                }
                //发起请求
                BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
                System.out.println("status:" + "===第" + i + "次插入" + pageSize + "条" + bulk.status());
            }
        }
    }













    //客户端对象
    private RestHighLevelClient client;
    @Before
    public void init() throws IOException {
        //创建es客户端
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.200.150",9200,"http")));
    }
    //关闭连接
    @After
    public void testrestclose() {
        try {
            if (client != null) {
                client.close();
                System.out.println("连接关闭");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
